<template>
    <div class="user-admin">
        <div class="top">
            <a-form layout="inline" :form="form" @submit="onSearch">
                <a-form-item>
                    <a-input placeholder="姓名"
                        v-decorator="['name',
                            { rules: [
                                { required: true, message: '请输入姓名' },
                            ] }
                        ]"
                    />
                </a-form-item>
                <a-form-item>
                    <a-button type="primary" html-type="submit" :loading="loading">搜索</a-button>
                    <a-button type="danger" class="btn-right" @click="onReset" :loading="loading">重置</a-button>
                </a-form-item>
            </a-form>
            <a-button type="primary" @click="onAdd">新增</a-button>
        </div>
        <a-table :columns="columns" :data-source="list" rowKey="userid"
            bordered
            class="table"
            :loading="loading"
            :pagination="pagination"
        >
            <span slot="action" slot-scope="text, record">
                <span class="action-btn" @click="onEdit(record)">修改</span>
                <span class="action-btn" @click="onDelete(record.userid, record.name)">删除</span>
            </span>
        </a-table>
        <a-modal :title="type==='add'?'新增员工':'编辑员工'"
            :visible="visible"
            :footer="null"
             @cancel="onCancel"
        >
            <a-form :form="form1" @submit="onAddSubmit">
                <a-form-item label="账号"
                    :label-col="formItemLayout.labelCol"
                    :wrapper-col="formItemLayout.wrapperCol"
                >
                    <a-input placeholder="请输入账号" 
                         v-decorator="['username',
                            { rules: [
                                { required: true, message: '请输入账号' },
                            ] }
                        ]"
                    />
                </a-form-item>
                <a-form-item label="姓名"
                    :label-col="formItemLayout.labelCol"
                    :wrapper-col="formItemLayout.wrapperCol"
                >
                    <a-input placeholder="请输入姓名" 
                         v-decorator="['name',
                            { rules: [
                                { required: true, message: '请输入姓名' },
                            ] }
                        ]"
                    />
                </a-form-item>
                <a-form-item label="部门名称"
                    :label-col="formItemLayout.labelCol"
                    :wrapper-col="formItemLayout.wrapperCol"
                >
                    <a-select style="width: 100%;"
                        placeholder="请选择部门"
                        v-decorator="['deptid', {
                            rules: [{ required: true, message: '请选择部门' },]
                        }]"
                    >   
                        <a-select-option v-for="(item, index) in depts" 
                            :key="index" :value="item.id"
                        >{{item.deptname}}</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="职务"
                    :label-col="formItemLayout.labelCol"
                    :wrapper-col="formItemLayout.wrapperCol"
                >
                    <a-select placeholder="请选择职务"
                        v-decorator="['roleId',
                            { rules: [
                                { required: true, message: '请选择职务' },
                            ] }
                        ]"
                    >
                        <a-select-option v-for="(item, index) in roleList" :key="index"
                            :value="item.id"
                        >{{item.name}}</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="密码"
                    :label-col="formItemLayout.labelCol"
                    :wrapper-col="formItemLayout.wrapperCol"
                    v-if="type === 'add'"
                >
                    <a-input placeholder="密码默认123" 
                         v-decorator="['password',
                            {   initialValue: '123',
                                rules: [
                                { required: true, message: '请输入密码' },
                            ] }
                        ]"
                    />
                </a-form-item>
                <a-form-item label="部门负责人"
                    :label-col="formItemLayout.labelCol"
                    :wrapper-col="formItemLayout.wrapperCol"
                >
                    <a-radio-group v-decorator="['isdepartment',
                            { initialValue: 0 }
                        ]">
                        <a-radio :value="1">是</a-radio>
                        <a-radio :value="0">否</a-radio>
                        </a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item :wrapper-col="{offset: 6}">
                    <a-button type="primary" html-type="submit" :loading="addLoading">提交</a-button>
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script>
import { getUsers, getRoles, getAllDepts, addUser, updateUser, deleteUser } from '@/services';

const columns = [
    { title: '姓名', dataIndex: 'name' },
    { title: '账号', dataIndex: 'username' },
    { title: '部门', dataIndex: 'deptname' },
    { title: '职务', dataIndex: 'role' },
    { title: '操作', key: 'action', align: 'center', scopedSlots: { customRender: 'action' } },
]

export default {
    name: 'UserAdmin',
    data(){
        return {
            visible: false,
            addLoading: false,
            formItemLayout: {
                labelCol: { span: 6 },
                wrapperCol: { span: 16 },
            },
            type: '',
            columns,
            loading: false,
            list: [],
            form: this.$form.createForm(this),
            form1: this.$form.createForm(this),
            pagination: { },
            roleList: [],
            depts: []
        }
    },
    mounted(){
        this.getUserList();
        this.getAllRoles();
        this.getDepts();
    },
    methods: {
        // 获取用户列表
        async getUserList(name='', page=1){
            this.loading = true;
            let res = await getUsers({ searchName: name, page });
            this.loading = false;
            if(res.responseObject){
                let pagination = { ...this.pagination };
                let { count, data } = res.responseObject;
                this.list = data;
                pagination.total = count;
                pagination.current = page;
                pagination.pageSize = 10;
                pagination.showTotal = (total, range) => `共找到 ${total} 条数据`
                this.pagination = pagination;
            }
        },
        // 获取所有职务列表
        async getAllRoles(){
            let res = await getRoles({ pageSize: 99 });
            if(res.responseObject) {
                this.roleList = res.responseObject.Result
            }
        },
        // 获取所有部门
        async getDepts(){
            let res = await getAllDepts();
            if(res.responseObject) {
                this.depts = res.responseObject;
            }
        },
        // 提交搜索按钮
        onSearch(e){
            e.preventDefault();
            const _that = this;
            this.form.validateFields((err, values) => {
                if (!err) {
                    _that.getUserList(values.name);
                }
            })
        },
        // 重置按钮
        onReset(){
            this.form.resetFields();
            this.getUserList();
        },
        // 新增按钮
        onAdd(){
            this.type = 'add';
            this.visible = true;
        },
        // 关闭modal
        onCancel(){
            this.visible = false;
            this.form1.resetFields();
        },
        // 删除按钮
        onDelete(id, text){
            const _that = this;
            this.$confirm({
                title: `确认删除 ${text} 吗? `,
                okText: "删除",
                okType: 'danger',
                cancelText: "取消",
                onOk(){
                    _that.onDeleteUser(id)
                }
            })
        },
        // 提交新增或修改
        onAddSubmit(e){
            e.preventDefault();
            const _that = this;
            const { type, editId, depts, roleList } = this;
            this.form1.validateFields((err, values) => {
                if (!err) {
                    if(type === 'add') _that.onAddUser(values);
                    if(type === 'edit') {
                        let item1 = depts.filter(item => item.id === values.deptid);
                        let item2 = roleList.filter(item => item.id === values.roleId);
                        let data = Object.assign(values, {
                            deptname: item1[0].deptname,
                            role: item2[0].name,
                            userid: editId
                        })
                        _that.onUpdateUser(data)
                    }
                }
            })
        },
        // 新增员工
        async onAddUser(params){
            this.addLoading = true;
            let res = await addUser(params);
            this.addLoading = false;
            const _that = this;
            if(res.success) {
                this.$message.success('新增员工成功', 1, ()=>{
                    _that.onCancel();
                    _that.getUserList('', _that.pagination.current);
                })
            }else if(!res.success && res.errorMessage){
                this.$message.error(res.errorMessage, 1)
            }
        },
        // 修改按钮
        onEdit(params){
            this.type = 'edit';
            this.visible = true;
            this.form1.getFieldDecorator('username');
            this.form1.getFieldDecorator('name');
            this.form1.getFieldDecorator('deptid');
            this.form1.getFieldDecorator('roleId');
            this.form1.getFieldDecorator('isdepartment');
            this.editId = params.userid;
            this.form1.setFieldsValue({
                username: params.username,
                name: params.name,
                deptid: params.deptid,
                roleId: params.roleId,
                isdepartment: params.isdepartment
            })
        },
        // 修改员工
        async onUpdateUser(params) {
            this.addLoading = true;
            let res = await updateUser(params);
            this.addLoading = false;
            const _that = this;
            if(res.success) {
                this.$message.success('修改员工成功', 1, ()=>{
                    _that.onCancel();
                    _that.getUserList('', _that.pagination.current);
                })
            }else if(!res.success && res.errorMessage){
                this.$message.error(res.errorMessage, 1)
            }
        },
        // 删除员工
        async onDeleteUser(id){
            this.loading = true;
            let res = await deleteUser(id);
            const _that = this;
            if(res.success){
                this.$message.success('删除员工成功', 1, ()=>{
                    _that.getUserList('', _that.pagination.count > 11 ? _that.pagination.current : 1);
                })
            }else if(res.errorMessage){
                this.loading = false;
                this.$message.error(res.errorMessage, 1)
            }
        }
    }
}
</script>

<style lang="less" scoped>
@import '../global.less';
    .user-admin{
        padding: 20px 30px;
        .top{
            margin-bottom: 20px;
            height: 40px;
            display: flex;
            justify-content: space-between;
            .btn-right{
                margin-left: 20px;
            }
        }
        .action-btn{
            color: @primary;
            margin: 0 10px;
            cursor: pointer;
        }
    }
</style>